const { Product, Category } = require('@models');
const { Op } = require('sequelize');
const { ApiResponse } = require('@shared/utils/response');
const ProductService = require('@services/product/product.service');

class ProductController {
  constructor() {
    // 绑定所有方法的this
    this.getProducts = this.getProducts.bind(this);
    this.getProduct = this.getProduct.bind(this);
    this.createProduct = this.createProduct.bind(this);
    this.updateProduct = this.updateProduct.bind(this);
    this.deleteProduct = this.deleteProduct.bind(this);
    this.updateStatus = this.updateStatus.bind(this);
    this.batchDelete = this.batchDelete.bind(this);
    this.batchUpdateStatus = this.batchUpdateStatus.bind(this);
  }

  /**
   * 获取商品列表
   */
  async getProducts(req, res) {
    try {
      const result = await ProductService.getProducts(req.query);
      return res.json(ApiResponse.success(result));
    } catch (error) {
      console.error('获取商品列表失败:', error);
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 获取商品详情
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async getProduct(req, res) {
    try {
      const { id } = req.params;
      console.log(`[ProductController] 获取商品详情，ID: ${id}`);
      
      const product = await ProductService.getProductById(id);
      
      if (!product) {
        console.log(`[ProductController] 未找到ID为${id}的商品`);
        return res.status(404).json({
          code: 404,
          message: '商品不存在'
        });
      }
      
      console.log(`[ProductController] 成功获取商品详情:`, JSON.stringify(product).slice(0, 200) + '...');
      return res.json({
        code: 200,
        message: 'success',
        data: product
      });
      
    } catch (error) {
      console.error('[ProductController] 获取商品详情出错:', error);
      return res.status(500).json({
        code: 500,
        message: `获取商品详情出错: ${error.message}`
      });
    }
  }

  /**
   * 创建商品
   */
  async createProduct(req, res) {
    try {
      console.log('创建商品请求数据:', req.body);
      
      // 验证必填字段
      if (!req.body.name) {
        return res.json(ApiResponse.fail('商品名称不能为空'));
      }
      
      if (!req.body.categoryId && req.body.categoryId !== 0) {
        return res.json(ApiResponse.fail('商品分类不能为空'));
      }
      
      if (!req.body.originalPrice && req.body.originalPrice !== 0) {
        return res.json(ApiResponse.fail('商品原价不能为空'));
      }
      
      if (!req.body.price && req.body.price !== 0) {
        return res.json(ApiResponse.fail('商品售价不能为空'));
      }
      
      const result = await ProductService.createProduct(req.body);
      return res.json(ApiResponse.success(result));
    } catch (error) {
      console.error('创建商品失败:', error);
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 更新商品
   */
  async updateProduct(req, res) {
    try {
      console.log(`更新商品, ID: ${req.params.id}`, req.body);
      
      // 验证必填字段
      if (req.body.name === '') {
        return res.json(ApiResponse.fail('商品名称不能为空'));
      }
      
      if (req.body.categoryId === null || req.body.categoryId === '') {
        return res.json(ApiResponse.fail('商品分类不能为空'));
      }
      
      if (req.body.originalPrice === null || req.body.originalPrice === '') {
        return res.json(ApiResponse.fail('商品原价不能为空'));
      }
      
      if (req.body.price === null || req.body.price === '') {
        return res.json(ApiResponse.fail('商品售价不能为空'));
      }
      
      const result = await ProductService.updateProduct(req.params.id, req.body);
      if (!result) {
        return res.json(ApiResponse.notFound('商品不存在'));
      }
      return res.json(ApiResponse.success(result));
    } catch (error) {
      console.error(`更新商品失败, ID: ${req.params.id}`, error);
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 删除商品
   */
  async deleteProduct(req, res) {
    try {
      const result = await ProductService.deleteProduct(req.params.id);
      if (!result) {
        return res.json(ApiResponse.notFound('商品不存在'));
      }
      return res.json(ApiResponse.success(null, '删除成功'));
    } catch (error) {
      console.error('删除商品失败:', error);
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 更新商品状态
   */
  async updateStatus(req, res) {
    try {
      const result = await ProductService.updateProductStatus(req.params.id, req.body.status);
      if (!result) {
        return res.json(ApiResponse.notFound('商品不存在'));
      }
      return res.json(ApiResponse.success(null, '状态更新成功'));
    } catch (error) {
      console.error('更新商品状态失败:', error);
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 批量删除商品
   */
  async batchDelete(req, res) {
    try {
      await ProductService.batchDeleteProducts(req.body.ids);
      return res.json(ApiResponse.success(null, '批量删除成功'));
    } catch (error) {
      console.error('批量删除商品失败:', error);
      return res.json(ApiResponse.error(error.message));
    }
  }

  /**
   * 批量更新商品状态
   */
  async batchUpdateStatus(req, res) {
    try {
      await ProductService.batchUpdateStatus(req.body.ids, req.body.status);
      return res.json(ApiResponse.success(null, '批量更新状态成功'));
    } catch (error) {
      console.error('批量更新商品状态失败:', error);
      return res.json(ApiResponse.error(error.message));
    }
  }
}

module.exports = new ProductController(); 